package calendar;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class WritePom {
	
	private static void createPom(String groupId,String artifactId,String version) throws Exception{
		
		String groupIdStr="groupId";
		String artifactIdStr="artifactId";
		String versionStr="version";
		
		String baseCont="<?xml version=\"1.0\"?>\n<project\nxsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\"\nxmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n<modelVersion>4.0.0</modelVersion>\n";
		String baseContEnd="</project>";
		groupId=groupId.replaceAll("\\.", "/");
		String path=basePath+groupId+"/"+artifactId+"/"+version+"/";
		String filePath=basePath+groupId+"/"+artifactId+"/"+version+"/"+artifactId+"-"+version+".pom";
		File file=new File(path);
		file.mkdirs();
		FileWriter writer=new FileWriter(filePath);
		
		writer.write(baseCont);
		writer.write("<"+groupIdStr+">"+groupId+"</"+groupIdStr+">\n");
		writer.write("<"+artifactIdStr+">"+artifactId+"</"+artifactIdStr+">\n");
		writer.write("<"+versionStr+">"+version+"</"+versionStr+">\n");
		writer.write(baseContEnd);
		writer.flush();
		writer.close();
		System.out.println("createFile:  "+filePath);
	}
	@SuppressWarnings("unchecked")
	public static void writePom(String path) throws Exception{
		
		String groupIdStr="groupId";
		String artifactIdStr="artifactId";
		String versionStr="version";
		
		String groupId;
		String artifactId;
		String version;
		
		InputStream stream = new FileInputStream(path);
		SAXReader reader = new SAXReader();
		Document doc = reader.read(stream);
		Element element = doc.getRootElement();
		
		element=element.element("dependencies");
		
		Iterator<Element> elementIterator=element.elementIterator("dependency");
		
		boolean flag=false;
		
		while(elementIterator.hasNext()){
			element=elementIterator.next();
			
			groupId=element.elementText(groupIdStr);
			artifactId=element.elementText(artifactIdStr);
			version=element.elementText(versionStr);
			
			for(String aa:existPom){
				if(groupId.equals(aa)){
					flag=true;
				}
			}
			if(flag==false){
				createPom(groupId, artifactId, version);
			}
			flag=false;
		}
	}
	
	private static String [] existPom={"xerces","spy","com.gozap.labi"};
	private static String basePath="C:/maven-3.0/repository/";
	
	public static void main(String[] args) throws Exception{
		
//		String path="pom.xml";
//		writePom(path);
		String path=System.getProperty("path");
		System.out.println(path);
	}
}
